package com.jt;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMybatis {
    /**
     * 规则说明：
     *      1.创建SqlSessionFactory   工厂模式
     *      2.获取SqlSession  数据库链接 + 传输器对象
     *      3.获取Mapper接口对象
     *      4.完成业务调用
     *      5.关闭链接
     * */
    @Test
    public void demo1() throws IOException {
        //1.1指定配置文件的根目录
        String resource = "mybatis-config.xml";
        //1.2通过I/O流 加载配置文件  org.apache.ibatis.io.Resources包路径
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //1.3实例化工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2获取SqlSession  通过SqlSession可以直接操作数据库
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3获取接口对象
        UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
        //4.调用接口方法
        List<User> userList = usermapper.findAll();
        System.out.println(userList);
        //5.暂时手动关闭链接
        sqlSession.close();
    }
}
